package com.eastseeway.radioproject.utils;

import android.util.Log;

import com.eastseeway.radioproject.base.Const;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class CRC16Check {
    private static final int POLYNOMIAL = 0x1021;
    private static final int INITIAL_VALUE = 0x0000;

    private static final int ALIGNMENT_BYTES = Const.STANDARD_DATA_LENGTH;
    public static int CRC16_CCITT_FALSE(String file) throws IOException{
        FileInputStream fis = new FileInputStream(file);
        FileChannel fileChannel = fis.getChannel();
        MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());

        int crc = INITIAL_VALUE; // initial value
        for (int index = 0; index < buffer.limit(); index++) {
            byte b = buffer.get(index);
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= POLYNOMIAL;
            }
        }
        fileChannel.close();
        fis.close();
        crc &= 0xffff;
        return crc;
    }

//    将文件进行64字节对齐
    public static void alignFile(String filePath) throws Exception {
        File file = new File(filePath);
        long fileLength = file.length();

        // Calculate the number of padding bytes needed
        int paddingBytes = (int) ((ALIGNMENT_BYTES - (fileLength % ALIGNMENT_BYTES)) % ALIGNMENT_BYTES);

        // No need to pad if the file is already aligned
        if (paddingBytes == 0) {
            Log.e("12121","File is already 64-byte aligned.");
            return;
        }

        try (RandomAccessFile raf = new RandomAccessFile(file, "rw");
             FileChannel channel = raf.getChannel()) {

            // Move to the end of the file
            channel.position(fileLength);

            // Create a buffer with the required number of padding bytes
            ByteBuffer buffer = ByteBuffer.allocate(paddingBytes);
            buffer.put(new byte[paddingBytes]); // Fill the buffer with 0x00
            buffer.flip(); // Prepare for writing

            // Write the padding bytes to the file
            while (buffer.hasRemaining()) {
                channel.write(buffer);
            }
            Log.e("12121",("File padded with " + paddingBytes + " bytes to be 64-byte aligned."));
        }
    }


}
